package com.falcon.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.falcon.core.utils.BeanUtils;
import com.falcon.domain.dos.MenuDO;
import com.falcon.domain.po.MenuPO;
import com.falcon.domain.req.MenuQuery;
import com.falcon.domain.req.MenuRequest;
import com.falcon.mapper.IMenuMapper;
import com.falcon.mvc.domain.BasePager;
import com.falcon.service.IMenuService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.swan.core.utils.TreeUtil;
import com.swan.mybatis.condition.Condition;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


@Slf4j
@Service
public class MenuService implements IMenuService {

    @Autowired
    private IMenuMapper menuMapper;

    @Override
    public Long save(MenuRequest request){
        MenuPO menuPO = BeanUtil.copyProperties(request, MenuPO.class);

        this.menuMapper.insertNotNull(menuPO);

        return menuPO.getId();
    }

    @Override
    public Boolean update(Long id, MenuRequest request){

        MenuPO menuPO = BeanUtil.copyProperties(request, MenuPO.class);
        menuPO.setId(id);

        return this.menuMapper.updateNotNull(menuPO);
    }

    @Override
    public Boolean deleteById(Long id) {

        return this.menuMapper.deleteById(id);
    }

    @Override
    public MenuDO queryById(Long id){

        MenuPO menuPO = this.menuMapper.selectById(id);

        MenuDO menuDO = BeanUtil.copyProperties(menuPO, MenuDO.class);

        return menuDO;
    }


    @Override
    public List<MenuDO> queryList(MenuQuery request){

        Condition condition = request.toCondition();

        List<MenuPO> poList = this.menuMapper.selectList(condition);

        List<MenuDO> doList = BeanUtil.copyToList(poList, MenuDO.class);

        return doList;
    }

    @Override
    public BasePager<MenuDO> queryPager(MenuQuery request){


        PageInfo<MenuPO> pageInfo = PageHelper.startPage(request.getPage(), request.getPageSize())
                .doSelectPageInfo(() -> this.menuMapper.selectList(request.toCondition()));

        return BeanUtils.toPager(pageInfo, MenuDO.class);
    }

    @Override
    public int batchDelete(List<Long> ids) {

        return this.menuMapper.deleteByIds(ids);
    }

    @Override
    public List<MenuDO> queryTree(MenuQuery request) {
        // 查询所有
        List<MenuDO> list = this.queryList(request);

        // 构建树
        List<MenuDO> treeResult = TreeUtil.buildSimpleTree(list, MenuDO::getId, MenuDO::getParentId,0l);

        return treeResult;
    }

}
